package com.real.fact.web.sale.domain;

import java.util.Date;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.apache.commons.lang.Validate;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;

import com.real.fact.web.customer.domain.Customer;


/**
 * @since Jul 3, 2011
 */
@Entity
@Table(name = "sale")
public class Sale {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "id", nullable = false)
  private long id;

  @Column(name = "date")
  private Date date;

  @OneToMany(cascade = CascadeType.ALL)
  @LazyCollection(value = LazyCollectionOption.FALSE)
  private List<ItemSale> items;

  @OneToMany(cascade = CascadeType.ALL, mappedBy="sale")
  private List<SalePayment> payments;
  
  @ManyToOne (fetch = FetchType.EAGER)
  private Customer customer;

  @Column(name = "total")
  private float total;

  protected Sale() {
  }

  public Sale(final Date theDate, final List<ItemSale> theItems,
      final Customer theCustomer) {
    Validate.notNull(theDate);
    Validate.notEmpty(theItems);
    date = theDate;
    items = theItems;
    customer = theCustomer;
    total = calculateTotalAmount();
  }

  public long getId() {
    return id;
  }

  public Date getDate() {
    return date;
  }

  public List<ItemSale> getItems() {
    return items;
  }

  public Customer getCustomer() {
    return customer;
  }

  private float calculateTotalAmount() {
    float total = 0;
    for (ItemSale item : items) {
      total += item.getAmount() * item.getPrice();
    }
    return total;
  }

  public float getTotal() {
    return total;
  }

  public List<SalePayment> getPayments() {
    return payments;
  }

}
